# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtWebKitWidgets import *


from controller.window_ui import Ui_MainWindow
from PyQt5 import QtGui, QtCore
from controller.hypervisor_manager import HypervisorManager
import sys
import numpy as np
import pyqtgraph as pg
import threading
import os


class MainWindow(QMainWindow, Ui_MainWindow):
    hpmng = HypervisorManager()
    vmname = ''

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.tableWidget_RowCount = len(MainWindow.hpmng.list())
        self.setupUi(self)

        # 3) Plot in chunks, adding one new plot curve for every 100 samples
        global chunkSize, maxChunks, startTime
        chunkSize = 100
        # Remove chunks after we have 60
        maxChunks = 60
        startTime = pg.ptime.time()
        global p5, data5, ptr5, curves
        curves = []
        data5 = np.empty((chunkSize + 1, 2))  # 点数据
        ptr5 = 0
        p5 = self.graphicsView
        p5.setXRange(-60, 0)
        p5.setYRange(1, 0)
        # update plot
        t = threading.Timer(1.0, self.myTimer)
        t.start()  ## 每一秒生成一个点

        # self.label_18.setText(QtGui.QApplication.translate("mainWindow", "CPU利用率：9%", None, QtGui.QApplication.UnicodeUTF8))
        #更新cpu利用率
        global cpu_label
        cpu_label = self.label_18

        MainWindow.hpmng.list()
        self.customContextMenuRequested()

    @staticmethod
    def updateCurve():
        # print 'updateCurve()方法开始'
        global p5, data5, ptr5, curves
        global cpu_label
        now = pg.ptime.time()
        for c in curves:
            c.setPos(-(now - startTime), 0)

        i = ptr5 % chunkSize
        if i == 0:
            curve = p5.plot()
            curves.append(curve)
            # 获取cpu利用率
            cpuAll = os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2]
            cpuIdleString = str(cpuAll.split(',')[3])[:-3]
            cpuIdleRate = float(float(cpuIdleString)/100)
            last = 1 - cpuIdleRate   #data5[-1]  # 描绘的值
            data5 = np.empty((chunkSize + 1, 2))
            data5[0] = last
            while len(curves) > maxChunks:
                c = curves.pop(0)
                p5.removeItem(c)
        else:
            curve = curves[-1]
        data5[i + 1, 0] = now - startTime
        #获取cpu利用率
        cpuAll = os.popen('top -bi -n 2 -d 0.02').read().split('\n\n\n')[1].split('\n')[2]
        cpuIdleString = str(cpuAll.split(',')[3])[:-3]
        cpuIdleRate = float(float(cpuIdleString) / 100)
        cpu_label.setText(
            QtGui.QApplication.translate("mainWindow", "CPU利用率：" + str((1 - cpuIdleRate) * 100) + "%", None,
                                         QtGui.QApplication.UnicodeUTF8))
        data5[i + 1, 1] = 1 - cpuIdleRate    #np.random.normal()   #描绘的值
        curve.setData(x=data5[:i + 2, 0], y=data5[:i + 2, 1])
        ptr5 += 1

    def myTimer(self):
        #print 'hello world'
        MainWindow.updateCurve()
        global t   # Notice: use global variable
        t = threading.Timer(1.0, self.myTimer)
        t.start()

    def customContextMenuRequested(self):
        self.label_5.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_6.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_7.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_11.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_12.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_13.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_20.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_21.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_22.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_26.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_27.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_28.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_32.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_33.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_34.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_38.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_39.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_40.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)

    def retranslateUi(self, mainWindow):
        super(MainWindow, self).retranslateUi(mainWindow)
        self.label_5.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_6.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_7.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_11.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_12.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_13.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_28.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_26.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_27.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_20.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_21.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_22.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_32.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_33.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_34.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_38.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_39.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_40.setPixmap(QtGui.QPixmap('logos/test.png'))

        self.label_8.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[0].vm_name, None, QtGui.QApplication.UnicodeUTF8))
        self.label_5.setWindowIconText(MainWindow.hpmng.list()[0].vm_name)
        self.label_9.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[1].vm_name, None, QtGui.QApplication.UnicodeUTF8))
        self.label_6.setWindowIconText(MainWindow.hpmng.list()[1].vm_name)
        self.label_10.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[2].vm_name, None, QtGui.QApplication.UnicodeUTF8))
        self.label_7.setWindowIconText(MainWindow.hpmng.list()[2].vm_name)
        self.label_14.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[3].vm_name, None, QtGui.QApplication.UnicodeUTF8))
        self.label_11.setWindowIconText(MainWindow.hpmng.list()[3].vm_name)

        i = 0
        while i < self.tableWidget_RowCount:
            item = self.tableWidget.item(i, 0)
            item.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[i].vm_name, None, QtGui.QApplication.UnicodeUTF8))
            item = self.tableWidget.item(i, 1)
            item.setText(QtGui.QApplication.translate("mainWindow", MainWindow.hpmng.list()[i].vm_status, None, QtGui.QApplication.UnicodeUTF8))
            i = i + 1

    def update_vm_status(self, vmname):
        i = 0
        index = 0
        while i < self.tableWidget_RowCount:
            item = self.tableWidget.item(i, 0)
            if item.text() == vmname:
                index = i
                break
            i = i + 1

        for vm in MainWindow.hpmng.list():
            if vm.vm_name == vmname:
                item = self.tableWidget.item(index, 1)
                item.setText(QtGui.QApplication.translate("mainWindow", vm.vm_status, None, QtGui.QApplication.UnicodeUTF8))

    def myListWidgetContext(self, point):
        popMenu = QtGui.QMenu()
        sender = self.sender()
        self.vmname = QtCore.QString(sender.windowIconText())
        #print '右键单击 ', self.vmname
        popMenu.addAction(QtGui.QAction(u'启动', self, triggered=self.startItem))
        popMenu.addAction(QtGui.QAction(u'关闭', self, triggered=self.shutdownItem))
        popMenu.addAction(QtGui.QAction(u'暂停', self, triggered=self.pauseItem))
        popMenu.addAction(QtGui.QAction(u'恢复', self, triggered=self.resumeItem))
        popMenu.exec_(QtGui.QCursor.pos())

    def startItem(self):
        #print 'startItem ' + self.vmname
        MainWindow.hpmng.start(self.vmname)
        self.update_vm_status(self.vmname)

    def shutdownItem(self):
        #print 'shutdownItem ' + self.vmname
        MainWindow.hpmng.shutdown(self.vmname)
        self.update_vm_status(self.vmname)

    def pauseItem(self):
        print 'pauseItem ' + self.vmname
        MainWindow.hpmng.pause(self.vmname)
        self.update_vm_status(self.vmname)

    def resumeItem(self):
        print 'resumeItem ' + self.vmname
        MainWindow.hpmng.resume(self.vmname)
        self.update_vm_status(self.vmname)

    # 向tabWidget添加tab页
    def add_label(self, windowIconText):
        sender = self.sender()
        self.vmname = unicode(QtCore.QString(sender.windowIconText()))
        print '左键单击 ', self.vmname
        if windowIconText not in self.label_list:
            self.label_list.append(windowIconText)
            self.newLabel = QtGui.QWidget()
            self.newLabel.setObjectName(windowIconText)
            self.tabWidget.addTab(self.newLabel, "")
            self.tabWidget.setTabText(self.tabWidget.indexOf(self.newLabel), QtGui.QApplication.translate("mainWindow", windowIconText, None, QtGui.QApplication.UnicodeUTF8))
            self.tabWidget.setCurrentIndex(self.label_list.index(windowIconText))
        else:
            self.tabWidget.setCurrentIndex(self.label_list.index(windowIconText))

        for vm in MainWindow.hpmng.list():
            if vm.vm_name == self.vmname:
                if vm.vm_status == '关机':
                    self.show_shutdown_tab_page()
                else:
                    self.show_started_tab_page()

    # todo
    def show_shutdown_tab_page(self):
        print 'show_shutdown_tab_page'

    # todo
    def show_started_tab_page(self):
        print 'show_started_tab_page'
        self.verticalLayout_8 = QtGui.QVBoxLayout(self.newLabel)
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.webView = QWebView(self.newLabel)
        url = 'http://ubuntu:6080/vnc.html?host=ubuntu&port=6080'
        self.webView.setUrl(QtCore.QUrl(url))
        self.webView.load(QtCore.QUrl(url))  # html
        #self.webView.setObjectName("webView")  # 网页
        self.verticalLayout_8.addWidget(self.webView)

    # todo 从关机到开机 及从开机到关机的界面变化
    def update_tab_page(self):
        print 'update_tab_page'


if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        mainwin = MainWindow()
        mainwin.show()
        app.exec_()
